package com.mostka.wsrpc.client.ui;

import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.mostka.wsrpc.shared.Channels;

import java.util.ArrayList;
import java.util.HashMap;

import java_cup.lalr_item;

public class MainWindow extends HorizontalPanel{

    private VerticalPanel messagesArea = new VerticalPanel();
    private VerticalPanel friendsBox = new VerticalPanel();
    private TextBox recipientNickBox = new TextBox();
    private HashMap<Integer, FlowPanel> messengersList = new HashMap<Integer, FlowPanel>();
    private ArrayList<MessageSendHandler> sendhandlers = new ArrayList<MessageSendHandler>();
    private ArrayList<MessengerSelectHandler> messengerSelectHandlers = new ArrayList<MessengerSelectHandler>();

    public MainWindow(){
        makeLayout();
        createChannelBox();
        createJoinButton();
    }

    private void makeLayout(){
        VerticalPanel vp = new VerticalPanel();
        FlowPanel fp = new FlowPanel();
        final Button sendButton = new Button("Send");
        final TextBox textInput = new TextBox();

        add(vp);
        add(friendsBox);
        add(new Button("Disconect", new ClickHandler() {
			public void onClick(ClickEvent event) {
				disconnectHandler.onDisconnectClick();
			}
		}));
        vp.add(messagesArea);
        vp.add(fp);
        fp.add(recipientNickBox);
        fp.add(textInput);
        fp.add(sendButton);

        vp.getElement().addClassName("layout");
        friendsBox.getElement().addClassName("friend-box");
        messagesArea.getElement().addClassName("messages-area");
        textInput.getElement().addClassName("text-input");
        recipientNickBox.getElement().addClassName("recipient");
        sendButton.setEnabled(false);
        recipientNickBox.setEnabled(false);

        sendButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                sendMessage(textInput.getText());
                textInput.setText("");
                sendButton.setEnabled(false);
            }
        });
        textInput.addKeyUpHandler(new KeyUpHandler() {
            @Override
            public void onKeyUp(KeyUpEvent keyUpEvent) {
                sendButton.setEnabled(textInput.getText().length()>3);
                if(sendButton.isEnabled() && keyUpEvent.getNativeKeyCode() == KeyCodes.KEY_ENTER){
            		sendMessage(textInput.getText());
                    textInput.setText("");
                    sendButton.setEnabled(false);
                }
            }
        });
    }
    public void clearBoard(){
    	messagesArea.clear();
    	friendsBox.clear();
    }

    public void setRecipient(String nick){
        recipientNickBox.setText(nick);
    }

    public void addMessenger(final int id, String nick, String avatarPath){
        FlowPanel layout = new FlowPanel();
        Image avatar = new Image();
        avatar.setUrl(avatarPath);
        InlineHTML nickSpan = new InlineHTML(nick);
        layout.getElement().addClassName("messenger");

        layout.addDomHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                selectMessenger(id);
            }
        },ClickEvent.getType());
        layout.add(avatar);
        layout.add(nickSpan);
        friendsBox.add(layout);

        messengersList.put(id,layout);

    }

    public void removeMessenger(int messengerId){
        FlowPanel fp = messengersList.get(messengerId);
        friendsBox.remove(fp);
        messengersList.remove(messengerId);
    }

    public void addMessage(final int id, String nick, String message){
        FlowPanel fp = new FlowPanel();
        InlineHTML userDetail = new InlineHTML(nick);
        InlineHTML messageSpan = new InlineHTML(message);

        fp.getElement().addClassName("message");
        userDetail.getElement().addClassName("nick");
        messageSpan.getElement().addClassName("text");

        fp.addDomHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                selectMessenger(id);
            }
        },ClickEvent.getType());

        fp.add(userDetail);
        fp.add(messageSpan);
        messagesArea.add(fp);
        if (messagesArea.getWidgetCount()>30){
            messagesArea.remove(0);
        }
        messagesArea.getElement().setScrollTop(messagesArea.getElement().getScrollHeight());
    }

    private void sendMessage(String text){
        for( MessageSendHandler handler:sendhandlers){
            handler.onMessageSend(text);
        }
    }
    
    private void selectMessenger(int messengerId){
        for( MessengerSelectHandler handler:messengerSelectHandlers){
            handler.onMessengerSelect(messengerId);
        }
    }
    
    private DisconnectHandler disconnectHandler;
    public void setDisconnectClickHandler(DisconnectHandler handler){
    	disconnectHandler = handler;
    }
    
    public void addSendHandler(MessageSendHandler handler){
        sendhandlers.add(handler);
    }
    public void removeSendHandler(MessageSendHandler handler){
        sendhandlers.remove(handler);
    }
    public void addMessengerSelectHandler(MessengerSelectHandler handler){
        messengerSelectHandlers.add(handler);
    }
    public void removeMessengerSelectHandler(MessengerSelectHandler handler){
        messengerSelectHandlers.remove(handler);
    }
    private ChoseChannelHandler choseChannelHandler;
    ListBox chanelsBox;
    Button joinButton;
    public void setChoseChannelHandler(ChoseChannelHandler handler){
    	choseChannelHandler=handler;
    }
    

    private void createChannelBox(){
    	chanelsBox = new ListBox();
    	for (String channelName : Channels.values) {
    		chanelsBox.addItem(channelName);
		}
    	chanelsBox.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				
			}
		});
    }
    private void createJoinButton(){
    	joinButton = new Button("Join", new ClickHandler() {
			public void onClick(ClickEvent event) {
				choseChannelHandler.onChannelChose(chanelsBox.getItemText(chanelsBox.getSelectedIndex()));
			}
		});
    }
    public void showJoinForm(){
    	FlowPanel fp = new FlowPanel();
    	fp.add(new InlineHTML("Select channel:"));
    	fp.add(chanelsBox);
    	fp.add(joinButton);
    	RootPanel.get().add(fp);
    }
    public static String getNick(){
        String nick = Window.prompt("Write your nick","Anonim"+Math.round(Math.random()*1000));
        while(nick==null || nick.length()<3){
            nick = Window.prompt("Chose your nick (min 3 characters)","Anonim"+Math.round(Math.random() * 1000));
        }
        return nick;
    }
}
